package com.buyouchina.web.action.privilege;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;

import com.buyouchina.bean.PageView;
import com.buyouchina.bean.privilege.Department;
import com.buyouchina.service.privilege.DepartmentService;
import com.buyouchina.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;

@Controller("DepartmentList")
public class DepartmentListAction extends BaseAction implements ModelDriven<Department>{
	private static final long serialVersionUID = 825851772407690814L;
	private Department department = new Department();
	@Resource(name="departmentServiceBean") private DepartmentService departmentService;
	
	@Permission(model="department",privilegeValue="view")
	public String execute() throws Exception {
		PageView<Department> pageView = new PageView<Department>(12,this.getPage());
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("name", "desc");
		if("true".equals(this.getQuery())){
			StringBuilder sb = new StringBuilder();
			List<Object> params = new ArrayList<Object>();
			if(department.getName()!=null && !"".equals(department.getName().trim())){
				sb.append(" o.name=?").append(params.size()+1);
				params.add(department.getName());
			}
			if(department.getName()!=null && !"".equals(department.getName().trim())){
				if(params.size()>0)  sb.append(" and ");
				sb.append(" o.name like ?").append(params.size()+1);
				params.add("%"+department.getName()+"%");
			}
			pageView.setQueryResult(
					departmentService.getScrollData(pageView.getFirstResult(), pageView.getMaxresult(),
							sb.toString(), params.toArray(), orderby));
			
		}else{
			pageView.setQueryResult(departmentService.getScrollData(pageView.getFirstResult(), pageView.getMaxresult(), orderby));
		}
		request.setAttribute("pageView", pageView);
		return SUCCESS;
	}
	public Department getModel() {
		return department;
	}
}
